<?php
// +----------------------------------------------------------------------
// | 07FLYSAAS [基于ThinkPHP5.0开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2025-2035 http://www.07fly.xyz
// +----------------------------------------------------------------------
// | Professional because of focus  Persevering because of happiness
// +----------------------------------------------------------------------
// | Author: 开发人生 <goodkfrs@qq.com>
// +----------------------------------------------------------------------

namespace app\plat\logic;

/**
 * 用户逻辑
 */
class TenUser extends PlatBase
{
    // 面包屑
    public static $crumbs = [];

    // 菜单Select结构
    public static $menuSelect = [];

    /**
     * 获取租户下用户列表
     */
    public function getTenUserList($where = [], $field = 'b.*', $order = 'id desc', $paginate = DB_LIST_ROWS)
    {
        $this->modelTenTenantUser->alias('a');
        $this->modelTenTenantUser->join = [
            ['ten_user b', 'a.ten_user_id=b.id'],
        ];
        $list = $this->modelTenTenantUser->getList($where, $field, $order, $paginate);
        foreach ($list as &$row) {
            $dpr = $this->modelTenUser->getTenUserDeptPositionRole($row['id']);
            $row['role_list'] = $dpr['role_list'];
            $row['role_list_name'] = arr2str(array_extract($dpr['role_list'], 'name'));
            $row['dept_list'] = $dpr['dept_list'];
            $row['dept_list_name'] = arr2str(array_extract($dpr['dept_list'], 'name'));
            $row['position_list'] = $dpr['position_list'];
            $row['position_list_name'] = arr2str(array_extract($dpr['position_list'], 'name'));
        }
        return $list;
    }

    /**
     * 获取列
     */
    public function getTenUserColumn($where = [], $field = true)
    {
        return $this->modelTenUser->getColumn($where, $field);
    }

    /**
     * 获取单个信息
     */
    public function getTenUserInfo($where = [], $field = 'b.*')
    {
        $this->modelTenTenantUser->alias('a');
        $this->modelTenTenantUser->join = [
            ['ten_user b', 'a.ten_user_id=b.id'],
        ];
        $info = $this->modelTenTenantUser->getInfo($where, $field);
        if (!empty($info)) {
            $info = $info->toArray();
            $dpr = $this->modelTenUser->getTenUserDeptPositionRole($info['id']);
            $info = array_merge($info, $dpr);
        }
        return $info;
    }

    /**
     * 添加
     */
    public function tenUserAdd($data = [])
    {
        $validate_result = $this->validateTenUser->scene('add')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateTenUser->getError()];
        }
        $tenantInfo= $this->modelTenTenant->getInfo(['id'=>TEN_TENANT_ID],'tenant_max_user');
        $userNum = $this->modelTenTenantUser->stat(['ten_tenant_id'=>TEN_TENANT_ID]);
        if($tenantInfo['tenant_max_user']<=$userNum){
            throw_response_error('租户用户数量已达上限');
        }
        $data['password'] = data_md5_key($data['password']);
        $userId = $this->modelTenUser->setInfo($data);
        $tenantUser = ['ten_tenant_id' => TEN_TENANT_ID, 'ten_user_id' => $userId];
        $result = $this->modelTenTenantUser->setInfo($tenantUser);

        $result && ten_log('新增', '新增系统用户，name：' . $data['username']);
        $url = url('show');
        return $result ? [RESULT_SUCCESS, '添加成功', $url] : [RESULT_ERROR, $this->modelTenUser->getError()];
    }

    /**
     * 编辑
     */
    public function tenUserEdit($data = [])
    {
        $validate_result = $this->validateTenUser->scene('edit')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateTenUser->getError()];
        }
        $data['remark'] = strip_tags($data['remark']);
        $url = url('show');
        $result = $this->modelTenUser->setInfo($data);
        $result && ten_log('编辑', '编辑用户，name：' . $data['username']);
        return $result ? [RESULT_SUCCESS, '编辑成功', $url] : [RESULT_ERROR, $this->modelTenUser->getError()];
    }

    /**
     * 修改密码
     */
    public function tenUserEditPwd($data = [])
    {
        $validate_result = $this->validateTenUser->scene('password')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateTenUser->getError()];
        }
        $user = $this->getTenUserInfo(['b.id' => $data['id']]);
        if (data_md5_key($data['old_password']) != $user['password']) {
            return [RESULT_ERROR, '旧密码输入不正确'];
        }
        $data['id'] = SYS_USER_ID;
        $data['password'] = data_md5_key($data['password']);
        $result = $this->modelTenUser->setInfo($data);

        $result && ten_log('编辑', '会员密码修改，id：' . $data['id']);

        $url = url('index/index');
        return $result ? [RESULT_SUCCESS, '密码修改成功', $url] : [RESULT_ERROR, $this->modelTenUser->getError()];
    }

    /**
     * 重置密码
     */
    public function tenUserResetPwd($data = [])
    {
        $validate_result = $this->validateTenUser->scene('resetpassword')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateTenUser->getError()];
        }
        if ($data['password'] != $data['password_confirm']) {
            throw_response_error('两次密码不一致');
        }
        $md5password = data_md5_key($data['password']);
        $where['id'] = ['in', $data['id']];
        $result = $this->modelTenUser->setFieldValue($where, 'password', $md5password);
        $result && ten_log('编辑', '重置密码修改，name：' . $data['username']);
        $url = url('index/index');
        return $result ? [RESULT_SUCCESS, '修改成功', $url] : [RESULT_ERROR, $this->modelTenUser->getError()];
    }

    /**
     * 删除
     */
    public function tenUserDel($data = [])
    {
        if (empty($data['id'])) {
            throw_response_error('选择执行的参数');
        }
        $ids = str2arr($data['id']);
        //防止误删超级权限
        if (in_array(IS_TENANT_ROOT, $ids)) {
            throw_response_error('默认管理员不能存在删除!!!');
        }
        $where['id'] = ['in', $ids];
        $result = $this->modelTenUser->deleteInfo($where, true);

        //删除用户与租户的关联
        $result &&  $this->modelTenTenantUser->deleteInfo(['ten_user_id' => ['in', $ids]], true);

        $result && ten_log('删除', '删除用户，where：' . http_build_query($where));
        return $result ? [RESULT_SUCCESS, '用户删除成功'] : [RESULT_ERROR, $this->modelTenUser->getError()];
    }

    /**
     * 绑定角色
     */
    public function setTenUserRole($data = [])
    {
        $url = url('show');
        if (IS_TENANT_ROOT == $data['id']) {
            return [RESULT_ERROR, '默认管理员不能绑定权限', $url];
        }
        $userIdArr = is_array($data['id']) ? $data['id'] : str2arr($data['id']);
        $roleIdArr = is_array($data['role_ids']) ? $data['role_ids'] : str2arr($data['role_ids']);

        foreach ($userIdArr as $userId) {
            //清除之前权限与用户的映射关联
            $delWhere = ['ten_user_id' => $userId, 'ten_tenant_id' => TEN_TENANT_ID];
            $this->modelTenUserRole->deleteInfo($delWhere, true);

            foreach ($roleIdArr as $roleId) {
                $combinedData = ['ten_user_id' => $userId, 'ten_role_id' => $roleId, 'ten_tenant_id' => TEN_TENANT_ID];
                $result = $this->modelTenUserRole->setInfo($combinedData);
            }
        }
        $result && ten_log('授权', '员工授权角色，id：' . $data['id']);
        return $result ? [RESULT_SUCCESS, '操作成功'] : [RESULT_ERROR, $this->modelTenUser->getError()];
    }

    /**
     * 设置用户权限节点
     */
    public function setTenUserMenus($data = [])
    {
        if (IS_TENANT_ROOT == $data['id']) {
            return [RESULT_ERROR, '默认管理员不能绑定角色'];
        }

        $userIdArr = is_array($data['id']) ? $data['id'] : str2arr($data['id']);
        $menuIdArr = is_array($data['menu_ids']) ? $data['menu_ids'] : str2arr($data['menu_ids']);

        foreach ($userIdArr as $userId) {
            //清除之前权限与用户的映射关联
            $delWhere = ['ten_user_id' => $userId, 'ten_tenant_id' => TEN_TENANT_ID];
            $this->modelTenUserMenu->deleteInfo($delWhere, true);

            foreach ($menuIdArr as $menuId) {
                $combinedData = ['ten_user_id' => $userId, 'ten_menu_id' => $menuId, 'ten_tenant_id' => TEN_TENANT_ID];
                $result = $this->modelTenUserMenu->setInfo($combinedData);
            }
        }
        $result && ten_log('授权', '员工授权菜单权限，id：' . $data['id']);
        return $result ? [RESULT_SUCCESS, '操作成功'] : [RESULT_ERROR, $this->modelTenUser->getError()];
    }

    /**
     * 设置职位
     */
    public function setTenUserPosition($data = [])
    {
        if (empty($data['position_ids']) || empty($data['id'])) {
            throw_response_error('数据缺少参数');
        }
        $userIdArr = is_array($data['id']) ? $data['id'] : str2arr($data['id']);
        $posiIdArr = is_array($data['position_ids']) ? $data['position_ids'] : str2arr($data['position_ids']);

        // 交叉组合两组数据
        foreach ($userIdArr as $userId) {

            $delWhere = ['ten_user_id' => $userId, 'ten_tenant_id' => TEN_TENANT_ID];
            $this->modelTenUserPosition->deleteInfo($delWhere, true);

            foreach ($posiIdArr as $posiId) {
                $combinedData = ['ten_user_id' => $userId, 'ten_position_id' => $posiId, 'ten_tenant_id' => TEN_TENANT_ID];
                $result = $this->modelTenUserPosition->setInfo($combinedData);
            }

        }
        $result && ten_log('编辑', '设置职位，name：' . $data['username']);
        $url = url('index/index');
        return $result ? [RESULT_SUCCESS, '操作成功', $url] : [RESULT_ERROR, $this->modelTenUser->getError()];
    }

    /**
     * 设置部门
     */
    public function setTenUserDept($data = [])
    {
        if (empty($data['dept_ids']) || empty($data['id'])) {
            throw_response_error('数据缺少参数');
        }
        $userIdArr = is_array($data['id']) ? $data['id'] : str2arr($data['id']);
        $deptIdArr = is_array($data['dept_ids']) ? $data['dept_ids'] : str2arr($data['dept_ids']);

        $combinedData = [];
        // 交叉组合两组数据
        foreach ($userIdArr as $userId) {

            $delWhere = ['ten_user_id' => $userId, 'ten_tenant_id' => TEN_TENANT_ID];
            $this->modelTenUserDept->deleteInfo($delWhere, true);

            foreach ($deptIdArr as $deptId) {
                $combinedData = ['ten_user_id' => $userId, 'ten_dept_id' => $deptId, 'ten_tenant_id' => TEN_TENANT_ID];
                $result = $this->modelTenUserDept->setInfo($combinedData);
            }

        }
        $result && ten_log('编辑', '设置部门，name：' . $data['username']);
        $url = url('index/index');
        return $result ? [RESULT_SUCCESS, '操作成功', $url] : [RESULT_ERROR, $this->modelTenUser->getError()];
    }

    /**
     * 查询条件
     *
     * @return array|mixed
     * Author: kfrs <goodkfrs@QQ.com> created by at 2020/7/19 0019
     */
    public function getWhere($data = [])
    {
        $where = [];
        if (!empty($data['keywords'])) {
            $where['b.username|b.mobile|b.realname'] = ['like', '%' . $data['keywords'] . '%'];
        }
        if (!empty($data['pid'])) {
            $users = $this->modelTenUserDept->getDeptAllUsers($data['pid']);
            $userIds = array_extract($users, 'id');
            $where['b.id'] = ['in', $userIds];
        }
        return $where;
    }

    /**
     * 获取指定用户下属员工列表信息
     * 取所有职位中，最大数据权限，找下属职位id
     * @param $stype
     * @return array （[0]=array(''1)）
     * Author: lingqifei created by at 2020/3/29 0029
     */
    public function getTenUserSubIds($id = 1, $type = 'selfson')
    {
        $userInfo = $this->getTenUserInfo(['b.id' => $id]);

        if (!empty($userInfo)) {

            //用户关联多个部门
            $deptIds = array_extract($userInfo['dept_list'], 'id');

            //根据职位查看权限，取值最大的职位id
            $positionList = $userInfo['position_list'];
            $dataRoles = array_extract($userInfo['position_list'], 'data_role');

            // 找到最大的 data_role 值
            $maxDataRole = max($dataRoles);

            // 找到 data_role 值最大的职位信息
            $maxPosition = array_reduce($positionList, function ($carry, $item) use ($maxDataRole) {
                if ($item['data_role'] === $maxDataRole) {
                    $carry = $item;
                }
                return $carry;
            }, null);

            //取所有职位中，最大数据权限，找下属职位id
            $positionSonIds = [];
            if (!empty($maxPosition)) {
                $positionSonIds = $this->modelTenPosition->getTenPositionAllSon($maxPosition['id']);
            }
            $allUserIds = [];
            foreach ($deptIds as $deptId) {
//                d('部门ID=>' . $deptId);
//                d('职位ID=>' . $maxDataRole);
//                d('===================================');
                switch ($maxDataRole) {

                    //1.当前部门内,当前职位下级职位用户id
                    case 1:
                        $userList = $this->modelTenUser->getTenUserLink($deptId, $positionSonIds);
                        break;

                    //2.当前部门所有员工id，不包含下级部门
                    case 2:
                        $userList = $this->modelTenUserDept->getDeptAllUsers($deptId, 'self');

                    //3.当前部门所有员工id，包含所有下级部门用户id
                    case 3:
                        $userList = $this->modelTenUserDept->getDeptAllUsers($deptId, 'selfson');

                    default:
                        break;
                }
                $allUserIds = array_merge($allUserIds, array_extract($userList, 'id'));
            }

        }//end if
        if ($type == 'selfson') $allUserIds[] = $id;
        if ($type == 'son') $allUserIds = arr_del_val($allUserIds, $id);//删除本身id
        $allUserIds = array_unique($allUserIds);//去除重复的
        return $allUserIds;
    }
}
